<?php

use Base\AdminController;
use JetBrains\PhpStorm\NoReturn;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Exceptions\LocalCacheException;
use WeChat\Media;
use Yaf\Dispatcher;

class UploadController extends AdminController
{

    /**
     * 文件上传
     * @return void
     * @throws InvalidResponseException
     * @throws LocalCacheException
     */
    #[NoReturn] public function fileAction():void
    {
        if (Request::instance()->isPost()) {
            $config = [
                'maxSize' => 4145728,
                'rootPath' => './public/uploads/',
                'saveName' => array('uniqid', ''),
                'autoSub'=>true,
            ];
            if (!is_dir($config['rootPath'])) mkdir($config['rootPath'], 0755, true);
            $upload = new Upload($config);
            $uploadInfo = $upload->upload();
            if (!$uploadInfo) $this->apiError($upload->getError());
            $url = getRequestHost(). "/" . $config['rootPath'] . $uploadInfo['file']['savepath'] . $uploadInfo['file']['savename'];
            if(Request::instance()->get("type") == "wechat") {
                $path = $config['rootPath'] . $uploadInfo['file']['savepath'] . $uploadInfo['file']['savename'];
                $config = Dispatcher::getInstance()->getApplication()->getConfig()->toArray()['wechat'];
                $wechat = new Media(['appid' => $config['AppId'], 'appsecret' => $config['AppSecret']]);
                $res = $wechat->uploadImg($path);
                $result = [
                    "url" => $url,
                    "name"=>$uploadInfo['file']['savename'],
                    "href"=>$res['url'],
                ];
            }else {
                $result = [
                    "url" => $url,
                    "name"=>$uploadInfo['file']['savename']
                ];
            }
            $this->apiSuccess($result ,"上传成功",20000);

        }
    }
}
